<script setup lang="ts">
import Motion from "../login/utils/motion";
import { useRouter } from "vue-router";
import { message } from "@/utils/message";
import { useNav } from "@/layout/hooks/useNav";
import type { FormInstance } from "element-plus";
import { useLayout } from "@/layout/hooks/useLayout";
import { bg, avatar, illustration } from "../login/utils/static";
import { ref, reactive, toRaw, onMounted, onBeforeUnmount } from "vue";
import { useDataThemeChange } from "@/layout/hooks/useDataThemeChange";
import dayIcon from "@/assets/svg/day.svg?component";
import darkIcon from "@/assets/svg/dark.svg?component";
import { sendCode, Captch, sendEmailCode } from "@/api/user";
import { register } from "@/api/user";
import { mainUrl } from "@/api/utils";
import { getSettings } from '@/api/setting';
const infos = ref({})

defineOptions({
  name: "Register"
});
const router = useRouter();
const loading = ref(false);
const ruleFormRef = ref<FormInstance>();

const { initStorage } = useLayout();
initStorage();

const { dataTheme, dataThemeChange } = useDataThemeChange();
dataThemeChange();
const { title } = useNav();

const ruleForm = reactive({
  username: "",
  password: "",
  email: "",
  phone: "",
  picode: "",
  code: "",
  rePassword: ""
});
const captchaSrc = ref("");
const onRegister = async (formEl: FormInstance | undefined) => {
  loading.value = true;
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log("这是什么：", valid);
      if (registerMode.value == "phone") {
        register({
          phone: ruleForm.phone,
          password: ruleForm.password,
          code: ruleForm.code,
          username: ruleForm.username
        }).then(res => {
          console.log("注册结果", res);
          if (res.data.code == 403) {
            message('该用户名已存在', { type: 'error' });
            loading.value = false;
          } else if (res.data.code == 400) {
            message('验证码错误', { type: 'error' });
            loading.value = false;
          } else if (res.data.code == 200) {
            message("注册成功", { type: "success" });
            router.push("/login");
          }
        });
      } else {
        register({
          email: ruleForm.email,
          password: ruleForm.password,
          code: ruleForm.code,
          username: ruleForm.username
        }).then(res => {
          console.log("邮箱注册结果", res);
          if (res.data.code == 403) {
            message('该用户名已存在', { type: 'error' });
            loading.value = false;
          } else if (res.data.code == 400) {
            message('验证码错误', { type: 'error' });
            loading.value = false;
          } else if (res.data.code == 200) {
            message("注册成功", { type: "success" });
            router.push("/login");
          }
        });
      }
    } else {
      console.log(valid)
      loading.value = false;
      message("请确认信息", { type: "error" });
      return fields;
    }
  });
};
const registerMode = ref("phone");
/** 使用公共函数，避免`removeEventListener`失效 */
function onkeypress({ code }: KeyboardEvent) {
  if (code === "Enter") {
    onRegister(ruleFormRef.value);
  }
}
onMounted(() => {
  window.document.addEventListener("keypress", onkeypress);
  getCaptch();
  getSettings(['indexbg1', 'mainlogo']).then((res) => {
    infos.value = res.data.data;
  });
});

onBeforeUnmount(() => {
  window.document.removeEventListener("keypress", onkeypress);
});
const hidecode = ref();
//生成图形验证码
const getCaptch = async () => {
  let { data } = await Captch({})
  hidecode.value = data.data.hcode
  captchaSrc.value = data.data.img
};
// 刷新图形验证码
const generateCaptcha = () => {
  getCaptch();
};
//发送验证码
const ToSendCode = async () => {
  if (registerMode.value == "phone") {
    let res = await sendCode({
      send_to: ruleForm.phone,
      message_type: "send_code",
      code: ruleForm.picode,
      hcode: hidecode.value
    });
    console.log("验证码结果：", res);
    if (res.data.state == 1) {
      message(res.data.data.msg, { type: res.data.data.status });
      sendbtn.value = true;
      const timer = setInterval(() => {
        if (countdown.value <= 0) {
          clearInterval(timer);
          sendbtn.value = false;
          countdown.value = 60;
        } else {
          countdown.value -= 1;
        }
      }, 1000);
    } else if (res.data.c_time) {
      message("发送频率过快", { type: "info" });
      sendbtn.value = true;
      countdown.value = res.data.c_time;
      const timer = setInterval(() => {
        if (countdown.value <= 0) {
          clearInterval(timer);
          sendbtn.value = false;
          countdown.value = 60;
        } else {
          countdown.value -= 1;
        }
      }, 1000);
    } else {
      message("验证码错误", { type: "error" });
    }
  } else {
    let res = await sendEmailCode({
      send_to: ruleForm.email,
      email_type: "send_code",
      code: ruleForm.picode,
      hcode: hidecode.value
    });
    console.log("邮箱验证码结果：", res);
    if (res.data.state == 1) {
      message('发送成功！', { type: 'success' });
      sendbtn.value = true;
      const timer = setInterval(() => {
        if (countdown.value <= 0) {
          clearInterval(timer);
          sendbtn.value = false;
          countdown.value = 60;
        } else {
          countdown.value -= 1;
        }
      }, 1000);
    } else if (res.data.c_time) {
      message("发送频率过快", { type: "info" });
      sendbtn.value = true;
      countdown.value = res.data.c_time;
      const timer = setInterval(() => {
        if (countdown.value <= 0) {
          clearInterval(timer);
          sendbtn.value = false;
          countdown.value = 60;
        } else {
          countdown.value -= 1;
        }
      }, 1000);
    } else {
      message("验证码错误", { type: "error" });
    }
  }
};
const sendbtn = ref(false);
const countdown = ref(60);
</script>

<template>
  <div class="select-none">
    <img :src="infos.indexbg1" class="wave" />
    <div class="flex-c absolute right-5 top-3 header">
      <img style='width:200px;margin-left: 25px;' @click="router.push('/home/home')" :src="infos.mainlogo" />
      <!-- 主题 -->
      <el-switch v-model="dataTheme" inline-prompt :active-icon="dayIcon" :inactive-icon="darkIcon"
        @change="dataThemeChange" />
    </div>
    <div class="login-container">
      <div class="img">
        <component :is="toRaw(illustration)" />
      </div>
      <div class="login-box">
        <div class="login-form">
          <!-- <avatar class="avatar" /> -->
          <img class="logoimg" :src="infos.mainlogo" />
          <Motion>
            <h2 class="outline-none">{{ title }}</h2>
          </Motion>

          <div class="register-mode-selector">
            <el-radio-group v-model="registerMode" class="change-mode">
              <el-radio-button label="phone">手机号注册</el-radio-button>
              <el-radio-button label="email">邮箱注册</el-radio-button>
            </el-radio-group>
          </div>

          <el-form ref="ruleFormRef" :model="ruleForm" size="large">
            <Motion :delay="150" v-if="registerMode == 'email'">
              <el-form-item prop="email" :rules="[
                {
                  required: true,
                  message: '请输入您的邮箱',
                  trigger: 'blur'
                },
                {
                  type: 'email',
                  message: '请输入正确的邮箱格式',
                  trigger: ['blur', 'change']
                }
              ]">
                <el-input v-model="ruleForm.email" clearable placeholder="邮箱" />
              </el-form-item>
            </Motion>
            <Motion :delay="150" v-if="registerMode == 'phone'">
              <el-form-item prop="phone" :rules="[
                { required: true, message: '请输入手机号', trigger: 'blur' },
                {
                  pattern: /^1[3-9]\d{9}$/,
                  message: '请输入正确的手机号格式',
                  trigger: 'blur'
                }
              ]">
                <el-input v-model="ruleForm.phone" clearable placeholder="手机号" />
              </el-form-item>
            </Motion>
            <Motion :delay="100">
              <el-form-item prop="picode">
                <div class="captcha-input-container">
                  <el-input v-model="ruleForm.picode" clearable placeholder="图形验证码" />
                  <img width="100" :src="captchaSrc" alt="图形验证码" @click="generateCaptcha()" />
                </div>
              </el-form-item>
            </Motion>
            <Motion :delay="100">
              <el-form-item prop="code">
                <div class="captcha-input-container">
                  <el-input v-model="ruleForm.code" clearable placeholder="请输入验证码" />
                  <el-button type="primary" @click="ToSendCode" width="100" :disabled="sendbtn">
                    {{
                      sendbtn ? `重新发送(${countdown}s)` : "发送验证码"
                    }}</el-button>
                </div>
              </el-form-item>
            </Motion>

            <Motion :delay="100">
              <el-form-item :rules="[
                {
                  required: true,
                  message: '请输入您的用户名',
                  trigger: 'blur'
                }
              ]" prop="username">
                <el-input v-model="ruleForm.username" clearable placeholder="用户名" />
              </el-form-item>
            </Motion>

            <Motion :delay="150">
              <el-form-item prop="password" :rules="[
                { required: true, message: '请输入密码', trigger: 'blur' },
                {
                  pattern: /^(?=.*[^\da-zA-Z\s]).{8,16}$/,
                  message: '密码需至少包含特殊字符且长度在8到16位之间',
                  trigger: 'blur'
                }
              ]">
                <el-input v-model="ruleForm.password" clearable show-password placeholder="密码" />
              </el-form-item>
            </Motion>
            <Motion :delay="150">
              <el-form-item prop="rePassword" :rules="[
                {
                  required: true,
                  message: '请再次输入密码',
                  trigger: 'blur'
                },
                {
                  validator: (rule, value, callback) => {
                    if (value !== ruleForm.password) {
                      callback(new Error('两次输入的密码不一致'));
                    } else {
                      callback();
                    }
                  },
                  trigger: 'blur'
                }
              ]">
                <el-input v-model="ruleForm.rePassword" clearable show-password placeholder="确认密码" />
              </el-form-item>
            </Motion>
            <div style="display: flex;justify-content: space-between;">
              <div class="regibutton" @click="router.push('/login')">去登录</div>
              <div class="regibutton"> <a href="/serviceterm.html">服务条款</a>
                <a href="/privacy.html">隐私政策</a>
              </div>
            </div>


            <Motion :delay="250">
              <el-button class="w-full mt-4" size="default" type="primary" :loading="loading"
                @click="onRegister(ruleFormRef)">
                注册
              </el-button>
            </Motion>
          </el-form>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
@import url("@/style/login.css");
</style>

<style lang="scss" scoped>
:deep(.el-input-group__append, .el-input-group__prepend) {
  padding: 0;
}

.regibutton {
  text-align: left;
  color: #409eff;
  font-size: 12px;

  a {
    padding-left: 10px
  }
}

.change-mode {
  margin-bottom: 20px;
}

.captcha-input-container {
  display: flex;
  align-items: center;
}

.header {
  display: felx;
  justify-content: space-between;
  width: 100%
}

@media screen and (max-width: 480px) {
  .logoimg {
    display: none;
  }
}
</style>
